
#include "Thread.h"

#if BASTERD_IS_WINDOWS

namespace basterd
{
	// --------------------------------------------------------------------
	// Windows-specific Mutex interface
	// --------------------------------------------------------------------
	Mutex::Mutex(void)
		: _mutex(0)
	{
		_mutex = CreateMutex (0, false, 0);
	}
	// --------------------------------------------------------------------
	Mutex::~Mutex(void)
	{
		if( _mutex )
		{
			CloseHandle( _mutex );
			_mutex = 0;
		}

	}
	// --------------------------------------------------------------------
	void Mutex::lock(void)
	{
		if( WaitForSingleObject (_mutex, INFINITE) == WAIT_FAILED)
		{
			BASTERD_WARNF("Couldn't lock mutex");
		}
	}
	// --------------------------------------------------------------------
	bool Mutex::tryLock(void)
	{
		DWORD rc = :: WaitForSingleObject (_mutex, 0);
		switch(rc)
		{
		// caller exited without unlocking the mutex.
		case WAIT_ABANDONED:
		{
			BASTERD_WARNF("Caller abandoned the mutex");
		}
		case WAIT_OBJECT_0:
		{
			// ok
			break;
		}
		// could not lock
		case WAIT_TIMEOUT:
		{
			return false;
		}
		// unknown errors
		default:
		{
			BASTERD_WARNF("Unexpected behavior");
		}
		case WAIT_FAILED:
		{
			BASTERD_WARNF("Eror calling WaitForSingleObject");
			return false;
		}
		}

		return true;
	}
	// --------------------------------------------------------------------
	void Mutex::unlock(void)
	{
		ReleaseMutex (_mutex);
	}
	// --------------------------------------------------------------------
}

#endif
